use datasource_connector::connector::SimpleDataSourceConnector;
use model_graph_types::{
    datasource::{DataSourceConnector, QueryCondition},
    modeling::{
        assistant::{Model, ModelSetting, ModelSettingBuilder, ModelType, ModelTypeSetting},
        system_meta_database, ClassGetter, Value,
    },
};
/// 通过模型名称获取模型和模型设置
pub async fn get_model(model_name: &String) -> anyhow::Result<(Model, ModelSetting)> {
    let dsc = SimpleDataSourceConnector::default();

    let model_value: Value = dsc
        .instance_query_one(
            &Some(system_meta_database()?),
            &system_meta_database()?,
            &Model::get_identifier()?,
            QueryCondition::with_attribute(String::from("name"), model_name.clone())?,
            None,
            None,
        )
        .await?;

    let model: Model = model_value.try_into()?;

    if let Ok(setting_value) = dsc
        .instance_query_one(
            &Some(system_meta_database()?),
            &system_meta_database()?,
            &ModelSetting::get_identifier()?,
            QueryCondition::with_attribute(
                String::from("model_identifier"),
                model.identifier.clone(),
            )?,
            None,
            None,
        )
        .await
    {
        let model_setting: ModelSetting = setting_value.try_into()?;
        //
        tracing::debug!("{:?}|{:?}", model, model_setting);

        Ok((model, model_setting))
    } else {
        Ok((model, ModelSettingBuilder::default().build()?))
    }
}

/// 通过模型类型获取到默认的模型以及provider名称
pub async fn default_model_name(mtype: ModelType) -> anyhow::Result<(String, String)> {
    let dsc = SimpleDataSourceConnector::default();

    //根据类型查默认的模型名称和provider名称
    let model_type_setting: ModelTypeSetting = dsc
        .instance_query_one(
            &Some(system_meta_database()?),
            &system_meta_database()?,
            &ModelTypeSetting::get_identifier()?,
            QueryCondition::with_attribute(String::from("model_type"), mtype.try_into()?)?,
            None,
            None,
        )
        .await?
        .try_into()?;

    Ok((
        model_type_setting.default_provider.clone(),
        model_type_setting.default_model.clone(),
    ))
}
